import { _decorator, Label, Sprite } from "cc";
import { app } from "db://app-game/core/app";
import { JsonUtil } from "db://app-game/core/utils/JsonUtil";
import {
  AsyncQueue,
  NextFunction,
} from "db://app-game/libs/collection/AsyncQueue";
import { ecs } from "db://app-game/libs/ecs/ECS";
import { CCComp } from "db://app-game/module/common/CCComp";
import { GameEvent } from "../../../common/config/GameEvent";
import { UIID } from "../../../common/config/GameUIConfig";
import { DBJoysitick } from "../../../common/db/db-joysitick/DBJoysitick";
import { DBLevel } from "../../../common/db/db-level/DBLevel";
import { DBLittleMonster } from "../../../common/db/db-little-monster/DBLittleMonster";
import { DBMap } from "../../../common/db/db-map/DBMap";
import { DBRole } from "../../../common/db/db-role/DBRole";
import { DBSkillIcon } from "../../../common/db/db-skill-icon/DBSkillIcon";
import { DBStaticCreature } from "../../../common/db/db-static-creature/DBStaticCreature";
import { DBStaticItems } from "../../../common/db/db-static-items/DBStaticItems";
import { smc } from "../../../common/ecs/model/SingletonModuleComp";
import { Home } from "../../home/Home";
import { Initialize } from "../Initialize";

const { ccclass, property } = _decorator;
/** 游戏资源加载 */
@ccclass("InitializeViewComp")
@ecs.register("LoadingView", false)
export class InitializeViewComp extends CCComp {
  @property({ type: Label, tooltip: "加载进度条提示文本" })
  promptLabel: Label = null!;
  @property({ type: Sprite, tooltip: "加载进度条" })
  progress: Sprite = null!;
  finished: number = 0;
  total: number = 0;
  loadPaths: { text: string; path: string }[] = [
    { text: "正在加载游戏资源...", path: "images" },
  ];

  protected start(): void {
    let queue: AsyncQueue = new AsyncQueue();
    // 1.注册事件
    this.addEvent();
    // 2.加载资源
    this.loadRes(queue);
    // 3.加载信息
    this.loadCustom();
    // 3.加载完成事件
    this.onCompleteCallback(queue);
  }

  private addEvent() {
    this.on(GameEvent.LoginSuccess, this.onHandler, this);
  }

  private onHandler(event: string) {
    switch (event) {
      case GameEvent.LoginSuccess:
        // 加载流程结束，移除加载提示界面
        this.ent.remove(InitializeViewComp);
        break;
    }
  }
  /** 加载游戏本地JSON数据（自定义内容） */
  private loadCustom() {
    // 加载游戏本地JSON数据的多语言提示文本
    this.promptLabel.string = "加载游戏数据...";
    return new Promise(async (resolve) => {
      await JsonUtil.loadAsync(DBLevel.DBName);
      await JsonUtil.loadAsync(DBRole.DBName);
      await JsonUtil.loadAsync(DBMap.DBName);
      await JsonUtil.loadAsync(DBStaticCreature.DBName);
      await JsonUtil.loadAsync(DBStaticItems.DBName);
      await JsonUtil.loadAsync(DBLittleMonster.DBName);
      await JsonUtil.loadAsync(DBJoysitick.DBName);
      await JsonUtil.loadAsync(DBSkillIcon.DBName);
      resolve(null);
    });
  }

  /** 加载资源 */
  private async loadRes(queue: AsyncQueue) {
    for (let i = 0; i < this.loadPaths.length; i++) {
      queue.push((next: NextFunction) => {
        const { text, path } = this.loadPaths[i];
        this.progress.fillRange = 0;
        this.promptLabel.string = text;
        app.res.loadDir(path, this.onProgressCallback.bind(this), next);
      });
    }
    // 开始
    queue.play();
  }

  /** 加载进度事件 */
  private onProgressCallback(finished: number, total: number) {
    this.finished = finished;
    this.total = total;

    let progress = finished / total;
    if (progress > this.progress.fillRange) {
      this.progress.fillRange = progress;
    }
  }

  /** 加载完成事件 */
  private onCompleteCallback(queue: AsyncQueue) {
    queue.complete = async () => {
      // 1.切换界面
      if (smc.account.AccountModel.id > -1) {
        this.onHandler(GameEvent.SceneChangeComplete);
      } else {
        // 初始化帐号模块
        smc.account.connect();
      }
    };
  }

  /** 重置 */
  reset(ent: Initialize): void {
    setTimeout(async () => {
      // 关闭加载界面
      app.gui.remove(UIID.Initialize);

      // 打开游戏主界面（自定义逻辑）
      const node = await app.gui.openAsync(UIID.Home);
      smc.home = ecs.getEntity<Home>(Home);
      if (node) {
        smc.home.jumpCompleted(node);
      }
    }, 500);
  }
}
